package top.jolyoulu.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Author: JolyouLu
 * @Date: 2024/2/7 20:51
 * @Description
 */
object Spark06_RDD_Operator_GroupBy2 {
  def main(args: Array[String]): Unit = {

    //准备环境 [*]:表示使用当前系统最大核
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("RDD")
    val sc: SparkContext = new SparkContext(sparkConf)

    val path: String = this.getClass.getClassLoader.getResource("datas/apache.log").toURI.getPath
    val rdd: RDD[String] = sc.textFile(path)
    val timeRDD: RDD[(String, Iterable[(String, Int)])] = rdd.map(data => {
      //截取日期
      val datas: String = data.split(" ")(3)
      //格式化
      val date: Date = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss").parse(datas)
      val time: String = new SimpleDateFormat("HH").format(date)
      (time, 1)
    }).groupBy(_._1) //根据time分组

    //将分组后合计
    timeRDD.map({
      case (hour,iter) => {
        (hour,iter.size)
      }
    }).collect().foreach(println)

    //关闭环境
    sc.stop()
  }

}
